﻿using Application.DTO.User;
using Application.DTO;
using Application.IService.User;
using Domain.Entity.User;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using MD5Hash;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.Text;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using JWT.Exceptions;
using Microsoft.AspNetCore.DataProtection;
using Newtonsoft.Json;
using System.Buffers.Text;
using System.Text.Json.Nodes;
using System.IdentityModel.Tokens.Jwt;
using Infrastructure.Repository.User;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using CSRedis;
using System.Reflection;
using Infrastructure.Common.JWT;

using Dapper;
using Microsoft.Data.SqlClient;

namespace ApiServer.Controllers.User
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("user")]
    [ApiController]
    [Authorize]
    public class UserController : BaseController<UserInfo>
    { 

        CSRedis.CSRedisClient redis = new CSRedis.CSRedisClient("127.0.0.1:6379");
        private readonly IUserService userService;
        private readonly JwtHelper jwtHelper;
       
        //注入配置文件夹
        private readonly IConfiguration Configuration;
      
        public UserController(IUserService userService, JwtHelper jwtHelper, IConfiguration configuration) : base(userService)
        {
            this.userService = userService;
            this.jwtHelper = jwtHelper;
            this.Configuration = configuration;
        }
        /// <summary>
        /// 测试用
        /// </summary>
        /// <returns></returns>
        [HttpGet("ccc")]
        public IActionResult ceshi()
        {
            List<Claim> clims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, "111"),
                new Claim(ClaimTypes.Name, "11111")
            };
            return Ok(jwtHelper.CreateTokenString(clims));
        }
        /// <summary>
        /// 刷新令牌
        /// </summary>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>`
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("refreshtoken")]
        public async Task<IActionResult> Refresh(string token)
        {
            return Ok(await userService.Refresh(token));
        }

        /// <summary>
        /// 读取appsettings文件中的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("Read_appsettings")]
        public async Task<IActionResult> Refresh_Token()
        {
            string a = Configuration.GetValue<string>("Logging:logLevel:Default");
            var b = Configuration["AllowedHosts"];
            //获取appsettings中jwt的秘钥
            JwtTokenOption c = Configuration.GetSection("JWTTokenOption").Get<JwtTokenOption>();

            #region
            //IJsonSerializer serializer = new JsonNetSerializer();
            //IDateTimeProvider provider = new UtcDateTimeProvider();
            //IJwtValidator validator = new JwtValidator(serializer, provider);
            //IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            //IJwtAlgorithm alg = new HMACSHA256Algorithm();
            //IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
            //var json = decoder.Decode(c.IssuerSigningKey,true);
            #endregion

            //return Ok(a);
            //return Ok(b);
            return Ok(c.IssuerSigningKey);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> UserLogin(LoginRequestDTO dto)
        {
            //对参数进行验证
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            return Ok(await userService.UserLogin(dto.UserName, dto.Password));
        }
        /// <summary>
        /// 注册账户    
        /// </summary>
        /// <param name="dto">注册信息</param>
        /// <returns></returns>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<IActionResult> RegisterAmount(RegisterAmountRequestDTO dto)
        {

            return Ok(await userService.RegisterAmount(dto));
        }
        [AllowAnonymous]
        [HttpGet("md5")]
        public IActionResult GetMD5(string a)
        {

            return Ok(a.GetMD5());
        }
        /// <summary>
        /// 找回密码，修改密码
        /// </summary>
        /// <param name="dto">用户名和密码信息</param>
        /// <returns></returns>
        [HttpPost("update")]
        [AllowAnonymous]
        public async Task<IActionResult> UpdatePassword(LoginRequestDTO dto)
        {
            return Ok(await userService.UpdatePassword(dto));
        }
        /// <summary>
        /// 用户分页查询
        /// </summary>
        /// <param name="UserName">用户昵称（即LoginName）</param>
        /// <param name="Pagesize"></param>
        /// <param name="Pageindex"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<IActionResult> Page(string? UserName = "", int Pagesize = 3, int Pageindex = 1,int DepartmentId=-1)
        {
            return Ok(await userService.Page(UserName, Pagesize, Pageindex, DepartmentId));
        }
        /// <summary>
        /// 管理员直接添加用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost("messageadduser")]
        public async Task<IActionResult> AddUser(User_AddDTO entity)
        {
            return Ok(await userService.AddUser(entity));
        }
        /// <summary>
        /// 逻辑删除用户
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteUser(string Ids)
        {
            return Ok(await userService.DeleteUser(Ids));
        }
        /// <summary>
        /// 修改自己的用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPut("user")]
        public async Task<IActionResult> UpdateUser(UserEditDTO entity)
        {
            return Ok(await userService.UpdateUser(entity));
        }
        /// <summary>
        /// 给用户分配角色
        /// </summary>
        /// <param name="RoleId">分配的角色ID</param>
        /// <param name="UserId">用户ID</param>
        /// <returns></returns>
        [HttpPut("allocation")]
        public async Task<IActionResult> AllocationRole(AllocationRoleDTO dto)
        {
            return Ok(await userService.AllocationRole(dto));
        }

    }
}
